package edu.example.manage.controller;

import edu.example.common.PowerCheck;
import edu.example.manage.annotation.MyDefineMapper;
import edu.example.manage.servlet.RoomMangeServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

@WebServlet("/room/manage/*")
public class RoomManageController extends HttpServlet {
    private static final RoomMangeServlet roomMangeServlet = new RoomMangeServlet();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 校验权限
        if (!PowerCheck.isAdmin(req)) {
            req.setAttribute("reMessage", "无权访问");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        // 转发servlet
        try {
            String[] uri = req.getRequestURI().split("/");
            Method[] methods = roomMangeServlet.getClass().getDeclaredMethods();
            String executionMethod = uri[uri.length-1].toLowerCase();
            System.out.println(executionMethod);
            for (Method method : methods) {
                MyDefineMapper annotation = method.getAnnotation(MyDefineMapper.class);
                if (annotation != null && annotation.value().equals(executionMethod)) {
                    method.invoke(roomMangeServlet, req, resp);
                    return;
                }
            }
            throw new RuntimeException("404");
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("reMessage", e.getMessage());
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }
}
